//  this library.
import 'dart:async';

import 'package:aliplayer_widget/aliplayer_widget_lib.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hktk_app/dao/course_dao.dart';
import 'package:hktk_app/main.dart';
import 'package:hktk_app/model/course/video_info_model.dart';
import 'package:hktk_app/model/course/video_save_model.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/pages/course/course_content_page.dart';
import 'package:hktk_app/pages/course/course_video_page1.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/back_button_widget.dart';
import 'package:hktk_app/widget/course/content_title_widget.dart';

/// 课程详情页面
class CourseDetailPage extends StatefulWidget {
  /// 视频相关信息
  final VideoInfoModel infoModel;

  /// 章节id
  final String chapterId;

  /// 章节名称
  final String chapterName;

  /// 栏目id
  final String columnId;

  /// 免费标志，true：免费/购买，false：未购买
  final bool free;

  const CourseDetailPage({
    super.key,
    required this.infoModel,
    required this.chapterId,
    required this.chapterName,
    required this.columnId,
    required this.free,
  });

  @override
  State<CourseDetailPage> createState() => _CourseDetailPageState();
}

class _CourseDetailPageState extends State<CourseDetailPage>
    with WidgetsBindingObserver, RouteAware {
  late BuildContext _context;

  /// 视频相关信息
  late VideoInfoModel _infoModel;

  /// 章节id
  late String _chapterId;

  /// 章节名称
  late String _chapterName;

  /// 是否横屏，true：横屏，false：竖屏
  late bool _isHorizontal;

  late GlobalKey<CourseVideoPageState> _videoPlayerKey;
  late StreamSubscription<EventCourseDetailVideoSwitch> listener;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      observer.subscribe(this, ModalRoute.of(context)!);
    });
    _videoPlayerKey = GlobalKey();
    _infoModel = widget.infoModel;
    _chapterId = widget.chapterId;
    _chapterName = widget.chapterName;
    _isHorizontal = false;
    WidgetsBinding.instance.addObserver(this);

    // 切换时重复触发了四次
    // 监听视频切换
    listener = eventBus.on<EventCourseDetailVideoSwitch>().listen((event) {
      // 暂停播放(异步)
      _videoPlayerKey.currentState?.pausePlayer();
      // 获取观看时长,播放完观看时长会滞空
      // static const int unknow = -1;
      // static const int idle = 0;
      // static const int initalized = 1;
      // static const int prepared = 2;
      // static const int started = 3;
      // static const int paused = 4;
      // static const int stopped = 5;
      // static const int completion = 6;
      // static const int error = 7;
      Map<String, VideoSaveModel> data = {};
      data[_infoModel.id!] = VideoSaveModel(
          ti: _videoPlayerKey.currentState?.getTi() ?? 0,
          fs: (event.infoModel.fs ?? false) ||
              _videoPlayerKey.currentState?.getPlayState() ==
                  FlutterAvpdef.completion);
      DataModel dataModel = dataUtilComm.dataModel;
      // 发送请求

      CourseDao.saveVideoRecords(
        industryCode: dataModel.industryId,
        examId: dataModel.examId,
        categoryId: dataModel.categoryId,
        columnId: widget.columnId,
        chapterId: event.chapterId,
        data: data,
      );
      // // 重置相关数据
      // _schedule = 0;
      // // ???
      // _isFs = true;
      // // 调用回调方法

      // 切换播放源
      _infoModel = event.infoModel;
      _chapterId = event.chapterId;
      _chapterName = event.chapterName;

      if (mounted) {
        setState(() {
          _videoPlayerKey.currentState?.switchSource(event).then((value) {
            // 这个setSate是改变对应讲义的
            // setState(() {
            //
            // });
          });
        });
      }
    });
  }

  @override
  void dispose() {
    super.dispose();

    eventBus.fire(EventCourseDetailBack());
    ToastUtil.loadingBoxRemove();
    WidgetsBinding.instance.removeObserver(this);
    listener.cancel();
  }

  @override
  Widget build(BuildContext context) {
    double bottom = ScreenUtil().bottomBarHeight;
    double top = ScreenUtil().statusBarHeight;
    _context = context;
    _isHorizontal = ScreenUtil().orientation == Orientation.landscape;
    // 管理系统后退手势
    return PopScope(
      // 内容显示
      canPop: true,
      // 系统后退手势发生时调用
      onPopInvoked: _onPopInvokeFun,
      // 内容显示
      child: Scaffold(
        backgroundColor: colorWhite2,
        // appBar:_isHorizontal?null: AppBar(
        //   centerTitle: true,
        //   title: Text(
        //     _infoModel.name!,
        //     maxLines: 1,
        //     overflow: TextOverflow.ellipsis,
        //   ),
        // ),
        body: SafeArea(child: OrientationBuilder(
            builder: (BuildContext context, Orientation orientation) {
          _isHorizontal = orientation == Orientation.landscape;
          // 横屏只显示视频组件
          if (orientation == Orientation.landscape) {
            return Container(
                decoration: BoxDecoration(color: Colors.black),
                child: Center(child: SizedBox(
                    height: 1.sh,
                    // width: 1.sw,
                    child: CourseVideoPage1(
                      key: _videoPlayerKey,
                      columnId: widget.columnId,
                      topChapterId: _chapterId,
                      videoId: _infoModel.id!,
                      aliyunVideoId: _infoModel.aliyunVideoId!,
                      isHorizontal: _isHorizontal,
                      videoTitle: _infoModel.name ?? "",
                      watchDuration: _infoModel.watchDuration ?? 0,
                      videoSwitchIngFun: _videoSwitchIngFun,
                    ))));
            return Column(
              children: [
                Expanded(
                    child: CourseVideoPage1(
                  key: _videoPlayerKey,
                  columnId: widget.columnId,
                  topChapterId: _chapterId,
                  videoId: _infoModel.id!,
                  aliyunVideoId: _infoModel.aliyunVideoId!,
                  isHorizontal: _isHorizontal,
                  videoTitle: _infoModel.name ?? "",
                  watchDuration: _infoModel.watchDuration ?? 0,
                  videoSwitchIngFun: _videoSwitchIngFun,
                ))
              ],
            );
          } else {
            // 竖屏正常显示
            return Column(
              children: [
                CourseVideoPage1(
                  key: _videoPlayerKey,
                  columnId: widget.columnId,
                  topChapterId: _chapterId,
                  videoId: _infoModel.id!,
                  aliyunVideoId: _infoModel.aliyunVideoId!,
                  isHorizontal: _isHorizontal,
                  videoTitle: _infoModel.name ?? "",
                  watchDuration: _infoModel.watchDuration ?? 0,
                  videoSwitchIngFun: _videoSwitchIngFun,
                ),
                Expanded(
                  child: Container(
                    color: colorWhite1,
                    child: Column(
                      children: [
                        // 提示购买，下载功能去掉
                        _titleItem(),
                        Expanded(
                          child: CourseContentPage(
                            columnId: widget.columnId,
                            chapterId: _chapterId,
                            chapterName: _chapterName,
                            videoId: _infoModel.id!,
                            free: widget.free,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            );
          }
        })),
      ),
    );
  }

  /// 标题组件
  _titleItem() {
    return ContentTitleWidget(
      title: _infoModel.name!,
      free: widget.free,
      columnId: widget.columnId,
    );
  }

  /// 返回按钮点击方法
  _onTapFunBack() {
    eventBus.fire(EventVideoBack());
  }

  /// 系统手势后退时调用方法
  void _onPopInvokeFun(bool didPop) {
    // 代码导航回退
    if (!didPop) {
    } else {
      //   系统手势按钮回退
    }
    eventBus.fire(EventVideoBack());
  }

  /// 视频切换回调
  void _videoSwitchIngFun({
    required String chapterId,
    required String chapterName,
    required VideoInfoModel infoModel,
  }) {
    setState(() {
      _infoModel = infoModel;
      _chapterId = chapterId;
      _chapterName = chapterName;
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
    } else if (state == AppLifecycleState.paused) {
      eventBus.fire(EventVideoBackground());
    }
  }

  @override
  void didPushNext() {
    if (_videoPlayerKey.currentState != null) {
      _videoPlayerKey.currentState!.pausePlayer();
    }
    super.didPushNext();
  }

  @override
  void didPopNext() {
    //   didPopNext
    if (_videoPlayerKey.currentState != null) {
      _videoPlayerKey.currentState!.playPlayer();
    }
    super.didPopNext();
  }
}
